import React, { Component } from 'react'
import { NavBar } from 'antd-mobile';
import './Category.scss'
import SearchInput from "../searchInput/SearchInput"
import myaxios from "../../utils/myaxios"
import axios from "axios"
export default class Category extends Component {
  constructor(props){
    super(props);
    const CancelToken = axios.CancelToken;
    this.source = CancelToken.source()
  }
  state = {
    categories: [],//商品分类信息
    categories_content: [],//右边菜单渲染的内容
    select_index: 0//当前选中的左边菜单
  }
  getCategories = (params) => {
    myaxios.get("/categories",{
      cancelToken:this.source.token
    }).then(res => {
      this.setCategories(res)
    }).catch(err => console.log(err))
  }
  //is_storaged 代表是否之前已经缓存过
  setCategories = (res,is_storaged) => {
    // 缓存请求的数据
    let categories_cache = {}
    // 如果之前没有缓存过
    if(!is_storaged){
      categories_cache = {date: Date.now(),categories: res}
      //缓存到本地
      localStorage.setItem('categories_cache', JSON.stringify(categories_cache))
    }
    this.setState({
      categories: res,
      categories_content: res[0].children
    })
  }
  componentWillUnmount(){
    this.source.cancel("取消分类菜单的请求")
  }
  componentDidMount() {
    //进来的时候先判断本地缓存是否过期
    //如果没有直接获取本地
    let categories_cache = JSON.parse(localStorage.getItem('categories_cache'))
    //如果本地缓存不为空
    if (categories_cache  && categories_cache.date) {
      //现在的时间
      let current_time = Date.now()
      //存储的时间
      let storage_time = categories_cache.date
      if (current_time - storage_time > 3600000) {
        //一小时过期
        console.log(1);
        this.getCategories()
      } else {
        //缓存没有过期
        //第二个参数代表是否已经缓存过
        this.setCategories(categories_cache.categories, true)
      }
    } else {
      this.getCategories()
    }
  }
  handleSelectClick = (e) => {
    //获取当前点击选中的项
    let select_index = parseInt(e.target.getAttribute('data-index'))
    if (select_index || select_index === 0) {
      this.setState({
        select_index,
        categories_content: this.state.categories[select_index].children
      })
    }
  }
  // 右边图片点击的时候
  handleProductItemClick = (e) => {
    if(e.target.getAttribute("data-index")){
      //获取当前点击选中的项
      let cid = parseInt(e.target.getAttribute('data-index'))
      this.props.history.push('/goodList?cid=' + cid)
    }
  }

  render() {
    return (
      <div className="yg-category">
        {/* 分类导航条开始 */}
        <div className="yg-category-nav">
          <NavBar className="category-nav-title">商品分类</NavBar>
        </div>
        {/* 分类导航条结束 */}
        {/* 分类搜索框开始 */}
        <div className="yg-category-search">
          <SearchInput></SearchInput>
        </div>
        {/* 分类搜索框结束 */}
        {/* 分类菜单栏开始 */}
        <div className="yg-category-content">
          {/* 利用冒泡的机制处理 */}
          <div className="content-left" onClick={this.handleSelectClick}>
            {this.state.categories.map((v, i) => {
              return <div
                data-index={i}
                className={this.state.select_index === i ? 'content-left-item active' : 'content-left-item'} key={v.cat_id}>
                <span data-index={i}>{v.cat_name}</span>
              </div>
            })}
          </div>
          <div className="content-right">
            {this.state.categories_content.map((v) => {
              return <div className="content-right-item" key={v.cat_id}>
                {/* 二级菜单标题开始 */}
                <div className="right-item-title">
                  {'/'}{v.cat_name}{'/'}
                </div>
                {/* 二级菜单标题结束 */}
                {/* 产品列表开始 */}
                <div className="product-list" onClick={this.handleProductItemClick}>
                  {v.children && v.children.map(vv => {
                    return <div data-index={vv.cat_id} key={vv.cat_id} className="product-list-item">
                      <div className="imageWrapper">
                        <img data-index={vv.cat_id} src={vv.cat_icon} alt="" />
                      </div>
                      <div className="item-title">
                        {vv.cat_name}
                      </div>
                    </div>
                  })}
                </div>
                {/* 产品列表结束 */}

              </div>
            })}
          </div>
        </div>
        {/* 分类菜单栏结束 */}
      </div>
    )
  }
}
